<template>
  <div class="three-wrapper">
    <div class="box" ref="box"></div>
    <div class="actions"></div>
  </div>
</template>

<script>
import * as d3 from 'd3'
import axios from 'axios'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
const clock = new THREE.Clock()
const FPS = 30 // 设置渲染频率为30FBS，也就是每秒调用渲染器render方法大约30次
const renderT = 1 / FPS // 单位秒  间隔多长时间渲染渲染一次
let timeS = 0
export default {
  components: {},
  props: {},
  data() {
    return {
      el: null,
      scene: null,
      camera: null,
      renderer: null,
      controls: null,
      animationFrameId: null,
      projection: null,
      extrudeOptions: {
        depth: -2, // 定义图形拉伸的深度，默认100 如果为负数, 为反向拉伸
        steps: 10, // 拉伸面方向分为多少级，默认为1
        bevelEnabled: true, // 表示是否有斜角，默认为true
        bevelThickness: 0, // 斜角的深度，默认为6
        bevelSize: 0, // 表示斜角的高度，高度会叠加到正常高度
        bebelSegments: 0, // 斜角的分段数，分段数越高越平滑，默认为1
        curveSegments: 0 // 拉伸体沿深度方向分为多少段，默认为1
      }
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.el = this.$refs['box']
    this.clock = new THREE.Clock()

    this.initThree()
  },
  activated() {},
  deactivated() {},
  updated() {},
  beforeDestroy() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId)
    }
  },
  destroyed() {},
  methods: {
    initThree() {
      // 初始化 - 开始
      this.initScene() // 核心： 场景
      this.initCamera() // 核心: 相机
      this.initRender() // 核心 渲染器
      this.initLight()
      this.initControls()
      this.animate()
      this.scene.add(this.setGridHelper(100 * 2, 10 * 2))
      this.scene.add(this.setAxesHelper(100000))
      // 初始化 - 结束

      // 绘制地图
      this.drawMap()
    },
    async drawMap() {
      const lineGroup = new THREE.Group()
      const exturdeGroup = new THREE.Group()
      const res = await this.getMapData()
      console.log('res', res)
      const regionCenter =
        (res.properties && res.properties.centroid) ||
        res.features[0]['properties']['center']
      this.projection = d3.geoMercator().center(regionCenter).translate([0, 0])
      res.features.slice(0).forEach(item => {
        // 获取每个区域的坐标数据
        var coordinates = item.geometry.coordinates
        // 1.循环坐标数据, 进行绘制
        coordinates.forEach(polygon => {
          if (polygon.length > 1) {
            polygon = [polygon] // 再包一层, 保持和其他的数据结构一致
          }

          polygon.forEach(p => {
            // 线条模型对象
            const lineObj = this.darwLine(p)
            // 拉伸处理
            const exturde = this.shapeToExturde(lineObj.shape)
            lineGroup.add(lineObj.mesh)
            // 拉伸的模型对象
            exturdeGroup.add(exturde)
          })
        })
      })
      let scaleSize = this.getModelScaleValue(lineGroup, 100)
      lineGroup.scale.set(scaleSize, scaleSize, scaleSize)
      exturdeGroup.scale.set(scaleSize, scaleSize, 1)
      this.scene.add(lineGroup)
      this.scene.add(exturdeGroup)
    },
    darwLine(pos) {
      // note: THREE.Geometry 已经被弃用了
      // const geo = new THREE.Geometry() // tips: 使用该代码会报错, 但是在script中可以正常的
      const geo = new THREE.BufferGeometry()
      const shape = new THREE.Shape()
      const lineMaterial = new THREE.LineBasicMaterial({
        color: '#bb3'
      })
      for (let i = 0; i < pos.length; i++) {
        const [x, y] = this.projection(pos[i])
        if (i === 0) {
          shape.moveTo(x, -y)
        }
        shape.lineTo(x, -y)
      }
      const points = shape.getPoints()
      geo.setFromPoints(points)
      const mesh = new THREE.Line(geo, lineMaterial)
      return {
        shape,
        mesh
      }
    },
    /**
     * 2D -> 3D
     * 通过shape 拉伸处理
     */
    shapeToExturde(shape) {
      const geometry = new THREE.ExtrudeGeometry(shape, this.extrudeOptions)
      // 正面材质
      const material1 = new THREE.MeshBasicMaterial({
        color: '#3192FF',
        transparent: true
      })
      // 侧面材质
      const material2 = new THREE.MeshBasicMaterial({
        color: '#30DAFE',
        transparent: true,
        opacity: 0.8
      })
      const mesh = new THREE.Mesh(geometry, [material1, material2])
      return mesh
    },
    getModelScaleValue(obj, referenceVal = 10000) {
      const size = this.getModelSize(obj)
      const { x, y, z } = size
      const maxVal = Math.max(x, y, z)
      const scaleValue = referenceVal / maxVal
      return scaleValue
    },
    getModelSize(model) {
      const box3 = new THREE.Box3()
      box3.expandByObject(model)
      const size = new THREE.Vector3()
      box3.getSize(size)
      return size
    },
    getMapData() {
      return axios.get('/aq-geojson/湖北省.json').then(res => res.data)
    },
    setGridHelper(size, divisions) {
      const gridHelper = new THREE.GridHelper(size, divisions)
      gridHelper.material.opacity = 0.8
      gridHelper.material.transparent = true
      return gridHelper
    },
    setAxesHelper(size) {
      return new THREE.AxesHelper(size)
    },
    // 初始化场景
    initScene() {
      this.scene = new THREE.Scene()
    },
    // 初始化相机
    initCamera() {
      const asp = this.el.offsetWidth / this.el.offsetHeight
      this.camera = new THREE.PerspectiveCamera(45, asp, 0.1, 10000000)
      this.camera.position.set(300, 300, 300)
      this.camera.lookAt(this.scene.position)
      this.scene.add(this.camera)
    },
    initRender(clearColor = '#000') {
      const width = this.el.offsetWidth
      const height = this.el.offsetHeight
      this.renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true
      })
      this.renderer.setPixelRatio(window.devicePixelRatio)
      this.renderer.setSize(width, height)
      this.el.append(this.renderer.domElement)
      // this.renderer.setClearColor(clearColor, 1) // 不设置背景色
    },
    initLight() {
      const ambientLight = new THREE.AmbientLight('#fff', 0.4)
      this.scene.add(ambientLight)
      const directionalLight = new THREE.DirectionalLight('#fff', 0.8)
      directionalLight.position.set(30, 30, 30).normalize()
      this.scene.add(directionalLight)
    },
    initControls() {
      this.controls = new OrbitControls(
        this.camera,
        this.renderer.domElement,
        {}
      )
      // dampingFactor 阻尼系数
      /* 值范围：0 ~ 1
      较小值 (如 0.01)：惯性更大，滑动时间更长
      较大值 (如 0.1)：惯性较小，停止更快
      推荐值：0.05 ~ 0.08 */
      this.controls.enableDamping = true
      this.controls.dampingFactor = 0.05
    },
    render() {
      const dt = this.clock.getDelta()
      const T = clock.getDelta()
      timeS = timeS + T
      if (timeS > renderT) {
        this.controls.update(dt)
        this.renderer.render(this.scene, this.camera)
        timeS = 0
      }
    },
    animate() {
      this.render()
      this.animationFrameId = requestAnimationFrame(this.animate)
    }
  },
  filters: {}
}
</script>
<style scoped lang="scss">
.three-wrapper {
  height: 100%;
  position: relative;
  .box {
    height: 100%;
    width: 100%;
    background: url(./images/map-bg.png);
    background-size: cover;
    background-repeat: no-repeat;
    overflow: hidden;
  }
  .actions {
    position: absolute;
    bottom: 10px;
    left: 10px;
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border: none;
      background-color: #409eff;
      color: #fff;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s ease;

      &:hover {
        background-color: #66b1ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      }
    }
  }
}
</style>
